﻿using System;
using System.Collections.Generic;
using ParserGenerator.Collections;
using ParserGenerator.Extensions;
using ParserGenerator.Input;
using ParserGenerator.ParserConstruction;

namespace ParserGenerator.GrammarConstruction
{
    [Serializable]
    public sealed class GrammarGoalDescriptor
    {
        public int Number { get; internal set; }
        public string Name { get; internal set; }
        public SourceContext Context { get; internal set; }
        public GrammarNonterminalSymbol StartSymbol { get; internal set; }
        public GrammarNonterminalSymbol GoalSymbol { get; internal set; }
        public GrammarProduction AcceptProduction { get; internal set; }
        public ParserAutomatonState State { get; internal set; }

        [NonSerialized]
        private ReadOnlySet<GrammarTerminalSymbol> _endMarkersWrapper;
        private HashSet<GrammarTerminalSymbol> _endMarkers;
        public ReadOnlySet<GrammarTerminalSymbol> EndMarkers
        {
            get
            {
                if (_endMarkers == null)
                    return null;
                if (_endMarkersWrapper == null)
                    _endMarkersWrapper = _endMarkers.AsReadOnly();
                return _endMarkersWrapper;
            }
        }

        internal GrammarGoalDescriptor()
        {
        }

        internal void SetEndMarkers(HashSet<GrammarTerminalSymbol> endMarkers)
        {
            if (endMarkers == null)
                throw new ArgumentNullException(nameof(endMarkers));
            _endMarkers = endMarkers;
        }

        internal void AddDefaultEndMarkers(IEnumerable<GrammarTerminalSymbol> endMarkers)
        {
            if (endMarkers == null)
                throw new ArgumentNullException(nameof(endMarkers));
            if (_endMarkers == null)
                _endMarkers = new HashSet<GrammarTerminalSymbol>();
            _endMarkers.UnionWith(endMarkers);
        }

        public sealed override string ToString()
        {
            return Name;
        }
    }
}
